import axios from 'axios'
import type { BaseResponse } from '@/types/common/response'

// 创建axios实例
const service = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL,
  timeout: 15000
})

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    // 添加认证token
    const token = localStorage.getItem('access_token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    const { code, message } = response.data as BaseResponse
    
    if (code === 0) {
      return response.data
    }
    
    // 处理业务错误
    console.error('API Error:', message)
    return Promise.reject(new Error(message))
  },
  (error) => {
    console.error('Network Error:', error)
    return Promise.reject(error)
  }
)

export default service